package com.example.nonameaa.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.nonameaa.Common.LogType;
import com.example.nonameaa.Common.Result;
import com.example.nonameaa.Common.ServiceException;
import com.example.nonameaa.utils.AopLogs;
import com.example.nonameaa.utils.TokenUtils;
import com.example.nonameaa.entity.User;
import com.example.nonameaa.service.UserService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author lhp
 * @since 2024-09-24
 */
@Controller
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;

    }
 
    /**
     * 新增用户信息
     */

    @AopLogs(operation = "用户", type = LogType.ADD)
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        try{
            User user1 = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
            if(user1 != null){
                return Result.error("帐号已存在");
            }
            userService.save(user);
        }catch (Exception e){
            if(e instanceof DuplicateKeyException){
                return Result.error("插入数据库错误");
            }else{
                return Result.error("系统错误");
            }
        }
        return Result.success(user);
    }

    /**
     * 查询所有User
     * @return
     */

    @GetMapping("/userList")
    public List<User> getUserList(){
        return userService.list(new QueryWrapper<User>().orderByAsc("id"));

    }

    /**
     * 通过Id查用户
     * @param id
     * @return
     */
    @GetMapping("/userById/{id}")
    public User findUserById(@PathVariable("id") Integer id) {
        return userService.getById(id);
    }

    /**
     * 根据id删除用户信息
     * @param id
     * @return
     */
    @AopLogs(operation = "用户", type = LogType.DELETE)
    @DeleteMapping("/deleteById/{id}")
    public boolean deleteUserById(@PathVariable("id") Integer id) {
        User currentUser = TokenUtils.getCurrentUser();
        if (id.equals(currentUser.getId())) {
            throw new ServiceException("不能删除当前的用户");
        }
         return userService.removeById(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AopLogs(operation = "用户", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        User currentUser = TokenUtils.getCurrentUser();

        if(currentUser != null && currentUser.getId() != null && ids.contains(currentUser.getId())){
            throw  new ServiceException("不能包含当前用户");
        }
        userService.removeByIds(ids);
        return Result.success();
    }
    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @AopLogs(operation = "用户", type = LogType.UPDATE)
    @PutMapping("/upgrateUser")
    public Boolean updateUserById(@RequestBody User user) {

       return userService.updateById(user);
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @param username
     * @param name
     * @return
     */
    @GetMapping("/selectByPage")
    public Result selectByPage( @RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                                @RequestParam String username,
                                @RequestParam String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByAsc("id");
        queryWrapper.like(StrUtil.isNotBlank(username), "username", username);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    /**
     * 批量导出EXCLE
     * @param username
     * @param name
     * @param response
     * @throws IOException
     */

    @GetMapping("/export")
    public void exportExcel( @RequestParam(required = false) String username,
                             @RequestParam(required = false) String name,
                             @RequestParam(required = false) String ids,
                             HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StrUtil.isNotBlank(ids)){
            List<Integer> idsArr1 = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
            queryWrapper.in("id", idsArr1);

        }else {
            queryWrapper.like("username", username);
            queryWrapper.like("name", name);
        }
        list = userService.list(queryWrapper);
        writer.write(list,true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        writer.close();
        outputStream.flush();
        outputStream.close();

    }



}







